package com.example.jpa.crud.search;

import com.example.jpa.crud.exception.UnknownFieldException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SortCondition {

    private String sql;

    public SortCondition() {
    }

    public SortCondition(String sql) {
        this.sql = sql;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    private static final SortCondition EMPTY = new SortCondition("");

    public static SortCondition of(List<String[]> list, Map<String, String> fieldToColumn) {
        if (list == null || list.isEmpty()) {
            return EMPTY;
        }
        final List<String> sortColumns = new ArrayList<>(list.size());
        for (String[] tuple : list) {
            if (tuple == null || tuple.length != 2) {
                continue;
            }
            final String columnName = fieldToColumn.get(tuple[0]);
            if (columnName == null) {
                throw new UnknownFieldException(tuple[0]);
            }
            sortColumns.add("`" + columnName + "` " + tuple[1]);
        }
        if (sortColumns.isEmpty()) {
            return EMPTY;
        }
        return new SortCondition("order by " + String.join(",", sortColumns) + " ");
    }

}
